import React, { PropsWithChildren, useEffect, useState } from "react";
import { connect } from 'react-redux';
import { push } from 'connected-react-router';
import { Descriptions, Button, Alert, message as Message, Upload } from "antd";
import { AxiosError } from 'axios';
import { LoadingOutlined, UploadOutlined } from "@ant-design/icons";
import { RouteComponentProps } from 'react-router';
import { CombinedState } from '../../store/reducers';
import { ProfileState } from '../../store/reducers/profiles';
import actions from '../../store/actions/profile';
import LOGIN_TYPES from '../../typings/login-types';
import NavHeader from '../../components/NavHeader';

import './index.less';
import store from "@/store/index";

const { Item: DescriptionsItem } = Descriptions;
//当前的组件有三个属性来源
//1.mapStateToProps的返回值 2.actions对象类型 3. 来自路由 4.用户传入进来的其它属性

type StateProps = ReturnType<typeof mapStateToProps>;
type DispatchProps = typeof actions;
interface Params { }
type RouteProps = RouteComponentProps<Params>;
type Props = PropsWithChildren<StateProps & DispatchProps & RouteProps>;

function Profile(props: Props) {
  // 上传图片，默认loading false.
  let [loading, setLoading] = useState(false);
  useEffect(() => {
    //组件加载后直接 发起验证请求,查看此用户是否已经登录过了,如果没有登录则提示错误
    const validateResult = props.validate();//返回是 Promise
    console.log(validateResult, 'validateResult=>一开始是多少？')
    validateResult.catch((error: AxiosError) => {
      console.log(error, 'error=>错误多少')
      Message.error(error && error.message);
    })
  }, []);

  const handleChange = (info: any) => {
    console.log(info, '上传图片=》')
    if (info.file.status === "uploading") {
      setLoading(true);
    } else if (info.file.status === "done") {
      let { success, data, message } = info.file.response;
      if (success) {
        setLoading(false);
        props.changeAvatar(data);
      } else {
        Message.error(message);
      }
    }
  };

  let content;//里存放着要渲染的内容
  if (props.loginState == LOGIN_TYPES.UN_VALIDATE) {
    //如果未验证则内容为null
    content = null;
  } else if (props.loginState == LOGIN_TYPES.LOGINED) {
    //如果已经登录显示用户信息

    const uploadButton = (
      <div>
        {loading ? <LoadingOutlined /> : <UploadOutlined />}
        <div className="ant-upload-text">上传</div>
      </div>
    );

    //如果已经登录显示用户信息
    content = (
      <div className="user-info">
        <Descriptions
          title="当前登录用户"
        >
          <DescriptionsItem label="用户名">{props.user.username}</DescriptionsItem>
          <DescriptionsItem label="邮箱">{props.user.email}</DescriptionsItem>

          <DescriptionsItem label="头像">
            <Upload
              name="avatar"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              action="http://localhost:6699/user/uploadAvatar"
              beforeUpload={beforeUpload}
              data={{ userId: props.user.id }}
              onChange={handleChange}
            >
              {props.user.avatar ? (
                <img
                  src={props.user.avatar}
                  alt="avatar"
                  style={{ width: "100%" }}
                />
              ) : (
                  uploadButton
                )}
            </Upload>
          </DescriptionsItem>


        </Descriptions>
        <Button type="primary"
          onClick={async () => {
            await props.logout();
            props.history.push('/login');
          }}
        >退出登录</Button>
      </div>
    );
  } else {
    //如果没有登录,则显示注册和登录按钮
    content = (
      <>
        <Alert
          type="warning"
          message="当前未登录"
          description="亲爱的用户你好，你当前尚未登录，请你选择注册或者登录"
        />
        <div style={{
          textALign: "center", padding: "50px"
        }}>
          <Button type="dashed" onClick={
            () => props.history.push("/login")
          }>
            登录
            </Button>
          <Button type="dashed"
            style={{ marginLeft: "50px" }}
            onClick={() => {
              props.history.push('/register')
            }}
          >
            注册
            </Button>
        </div>
      </>
    )
  }

  return (
    <section>
      <NavHeader history={props.history}>个人中心</NavHeader>
      {content}
    </section>
  )
}

// const mapStateToProps = (state: CombinedState): ProfileState => state.profile

// export default connect(mapStateToProps, actions)(Profile)


const mapStateToProps = (initialState: CombinedState): ProfileState => initialState.profile;

export default connect(mapStateToProps, actions)(Profile);

// 上传前判断。。
function beforeUpload(file: any) {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJpgOrPng) {
    Message.error("你只能上传JPG/PNG 文件!");
  }
  const isLessThan2M = file.size / 1024 / 1024 < 2;
  if (!isLessThan2M) {
    Message.error("图片必须小于2MB!");
  }
  return isJpgOrPng && isLessThan2M;
}